﻿// See https://aka.ms/new-console-template for more information

using JWT;
using JWT.Algorithms;
using JWT.Builder;
using JWT.Exceptions;
using JWT.Serializers;
using System.Text.Json;
using System.Text.Json.Nodes;

string CreateToken()
{
    var token = JwtBuilder.Create()
                      .WithAlgorithm(new HMACSHA256Algorithm())
                      .WithSecret(["7025BE62-7FC2-4D1F-9694-258BAD25DAB4"])
                      .AddClaim("iss", "https://www.madeinlean.com/home")
                      .AddClaim("iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds())
                      .AddClaim("exp", DateTimeOffset.UtcNow.AddDays(2).ToUnixTimeSeconds())
                      .AddClaim("nbf", DateTimeOffset.UtcNow.ToUnixTimeSeconds())
                      .AddClaim("jti", Guid.NewGuid().ToString())
                      .AddClaim("sub", 8)
                      .Encode();
    return token;
}



const string strToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvd3d3Lm1hZGVpbmxlYW4uY29tXC9ob21lIiwiaWF0IjoxNzAzNTgwODgwLCJleHAiOjE3MDM2NjcyODAsIm5iZiI6MTcwMzU4MDg4MCwianRpIjoiZ2N5WHZ2RTc2MkI0Rmc5WSIsInN1YiI6OCwicHJ2IjoiODdlMGFmMWVmOWZkMTU4MTJmZGVjOTcxNTNhMTRlMGIwNDc1NDZhYSJ9.tXPY4UjrPGqVBWrWUAlaBgp4IWR3ahDMU9IjKt3-rmo";
var token = CreateToken();


try
{
    IJsonSerializer serializer = new JsonNetSerializer();
    IDateTimeProvider provider = new UtcDateTimeProvider();
    IJwtValidator validator = new JwtValidator(serializer, provider);
    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
    IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
    IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);

    var strJson = decoder.Decode(token, "7025BE62-7FC2-4D1F-9694-258BAD25DAB4");
    var json = JsonSerializer.Deserialize<JsonObject>(strJson);
    Console.WriteLine(token);
    Console.WriteLine(json?.ToJsonString());

    strJson = decoder.Decode(strToken, "S0PoOfPJQbAV01wNNibLvEcUUUBqqbZPWjnhewTvqy4oygMPhKoCrVIAf3Ctf7b2");
    json = JsonSerializer.Deserialize<JsonObject>(strJson);
    Console.WriteLine(strToken);
    Console.WriteLine(json?.ToJsonString());    
}
catch (TokenNotYetValidException)
{
    Console.WriteLine("Token is not valid yet");
}
catch (TokenExpiredException)
{
    Console.WriteLine("Token has expired");
}
catch (SignatureVerificationException)
{
    Console.WriteLine("Token has invalid signature");
}

Console.ReadKey();